from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import os
import os.path

import re
import sys
import tarfile
from six.moves import urllib

import json

import numpy as np
import tensorflow as tf
from matplotlib import pyplot as plt
from matplotlib.font_manager import FontProperties
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

from utils import visualization_utils as vis_util
from utils import label_map_util

class NodeLookup(object):
    def __init__(self,label_path=None):
        if not label_path:
            tf.logging.fatal('please specify the label file.')
            return
        self.node_lookup = self.load(label_path)

    def load(self, label_path):
        if not tf.gfile.Exists(label_path):
            tf.logging.fatal('File does not exist %s', label_path)
    # Loads mapping from string UID to human-readable string
        proto_as_ascii_lines = tf.gfile.GFile(label_path).readlines()
        id_to_human = {}
        for line in proto_as_ascii_lines:
            if line.find(':') < 0:
                continue
            _id, human = line.rstrip('\n').split(':')
            id_to_human[int(_id)] = human
        return id_to_human
        
    def id_to_string(self, node_id):
        if node_id not in self.node_lookup:
            return ''
        return self.node_lookup[node_id]
def create_graph(model_file=None):
    #if not model_file:
        #model_file = FLAGS.model_file
    with open(model_file, 'rb') as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
        _ = tf.import_graph_def(graph_def, name='')

def vehicle_classification(img_path, model_file, label_file, num_top_predictions):
    detection_graph = tf.Graph()
    with detection_graph.as_default():
        if not tf.gfile.Exists(img_path):
            tf.logging.fatal('File does not exist %s', img_path)          
        image_data = open(img_path, 'rb').read()
        create_graph(model_file)
        with tf.Session() as sess:
            softmax_tensor = sess.graph.get_tensor_by_name('final_probs:0')
            predictions = sess.run(softmax_tensor,{'input:0': image_data})
            predictions = np.squeeze(predictions)
           # Creates node ID --> English string lookup.
            node_lookup = NodeLookup(label_file)
            top_k = predictions.argsort()[-num_top_predictions:][::-1]
            human_string = node_lookup.id_to_string(top_k[0])
            top_names = human_string
    return predictions,node_lookup,top_k, top_names
